//
// Created by draw on 19-5-29.
//

#include "Serial.h"

Serial::Serial(
        Usart *uart,
        Gpio *txPort,
        Gpio *rxPort,
        u32 txPin,
        u32 rxPin,
        Dma *rxDma,
        DmaStream *rxDs,
        Dma_Channel rxDc
              )
        :
        UART(uart),
        TxPort(txPort),
        RxPort(rxPort),
        TxPin(txPin),
        RxPin(rxPin),
        RxDma(rxDma),
        RxDs(rxDs),
        RxDc(rxDc)
{

}

void Serial::SetUpRxDma(u8 *buf, u32 len)
{
    AFIO AF;
    if (UART == USART1 || UART == USART2)
    {
        AF = AF7_Usart1_3;
    } else
    {
        AF = AF8_Usart4_6;
    }


    TxPort->AfPp(TxPin);
    TxPort->Speed(TxPin, Speed_Very_High);
    TxPort->Pull(TxPin, Pull_Up);
    TxPort->Alternate(TxPin, AF);

    RxPort->AfPp(RxPin);
    RxPort->Speed(RxPin, Speed_Very_High);
    RxPort->Pull(RxPin, Pull_Up);
    RxPort->Alternate(RxPin, AF);

    RxDs->DateNum(len);
    RxDs->Mem0Addr((u32) (buf));
    RxDs->PerAddr((u32) &(UART->DR));

    RxDs->Select(RxDc);
    RxDs->Priority(Priority0);
    RxDs->MemSet(Mem8, Mem_Inc);
    RxDs->PerSet(Per8, Per_Fix);
    RxDs->Dir(Per_To_Mem);
    RxDs->Circular(True);
    RxDs->FlowCtrl(Dma_Ctrl);
    RxDs->Start();

    UART->Reset();
    UART->Baud(115200);

    UART->CR1 |= 1 << 4;
    UART->CR3 |= 1 << 6;

    UART->Enable(Tx_Rx_Both);
    UART->PrintLn("Serial Init...");
}
